#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <error.h>
#include <unistd.h>
#include <string>

using namespace std;

#define BUFFERSIZE 256

void writeToFile(int fd)
{
    /* 向文件写数据 */
    string buf = "hello world";
    int wirteBytes = write(fd, buf.c_str(), buf.size());
    cout << "wirteBytes = " << wirteBytes << endl;
}

void readFromFile(int fd)
{
    /* 向文件读数据 */
    char buffer[BUFFERSIZE] = {0};
    int readBytes = read(fd, buffer, sizeof(buffer));
    cout << "readBytes: " << readBytes  << " buffer:" << buffer << endl;
}

int main()
{
    const char * filename = "./test1.txt";
    int fd1 = open(filename, O_CREAT | O_RDWR, 0644);  //返回文件描述符,多种功能中间加上或运算符 
    //0644可读可写可执行，0代表二进制
    if(fd1 == -1)
    {
        /* 打印错误原因 */
        perror("file open error");
    }
    cout << "fd1 = " << fd1 << endl;

    //writeToFile(fd1);     //为什么写入就读不出来了
    readFromFile(fd1);
    

    close(fd1);

#if 0
    filename = "./test2.txt";
    int fd2 = open(filename, O_CREAT | O_RDWR, 0644);  //返回文件描述符,多种功能中间加上或运算符 
    //0644可读可写可执行，0代表二进制
    if(fd2 == -1)
    {
        /* 打印错误原因 */
        perror("file open error");
    }
    cout << "fd2 = " << fd2 << endl;

    close(fd1);

    filename = "./test3.txt";
    int fd3 = open(filename, O_CREAT | O_RDWR, 0644);  //返回文件描述符,多种功能中间加上或运算符 
    //0644可读可写可执行，0代表二进制
    if(fd3 == -1)
    {
        /* 打印错误原因 */
        perror("file open error");
    }
    cout << "fd3 = " << fd3 << endl;

    /* 关闭文件 回收资源 */
    //close(fd1);
    close(fd2);
    close(fd3);
#endif
    while(1)
    {
        sleep(3);
    }

    return 0;
}